package app.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.hsqldb.rights.User;

import app.exceptions.ReportException;
import app.models.Usuario;


public class ReportUtils {
	
	
    @SuppressWarnings("deprecation")
    public static JasperReport loadReport(String paramInputStream) throws ReportException {
    	
        JasperReport localJasperReport = null;
        
        try {
        	
            localJasperReport = (JasperReport) JRLoader.loadObject(paramInputStream);
            
        } catch (JRException ex) {
            Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            
            throw new ReportException(ex.getMessage(), ex);
        } catch (Exception ex) {
            Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            
            throw new ReportException(ex.getMessage(), ex);
        }
        
        return localJasperReport;
    }
	
    
	@SuppressWarnings({ "rawtypes", "unchecked" })
    public static byte[] exportToPdf(String paramInputStream, Map paramMap, List paramList) throws ReportException {
		
        try {
            JasperReport localJasperReport = loadReport(paramInputStream);
            JasperPrint localJasperPrint = JasperFillManager.fillReport(localJasperReport, paramMap, new JRBeanCollectionDataSource(paramList, false));
            
            return JasperExportManager.exportReportToPdf(localJasperPrint);
        } catch (Exception ex) {
            Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            
            throw new ReportException(ex.getMessage(), ex);
        }
    }
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
    public static byte[] exportToXls(String paramInputStream, Map paramMap, List paramList) throws ReportException {
		
        ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
        
        try {
            JRXlsxExporter localJRXlsExporter = new JRXlsxExporter();
            JasperReport localJasperReport = loadReport(paramInputStream);
            JasperPrint localJasperPrint = JasperFillManager.fillReport(localJasperReport, paramMap, new JRBeanCollectionDataSource(paramList, false));
            localJRXlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, localJasperPrint);
            localJRXlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, localByteArrayOutputStream);
            localJRXlsExporter.exportReport();
            
        } catch (Exception localException) {
            Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, null, localException);
            
            throw new ReportException(localException.getMessage());
        }
        
        return localByteArrayOutputStream.toByteArray();
    }
	
	
    @SuppressWarnings("rawtypes")
	public static void exportPDFToResponse(
			HttpServletResponse paramHttpServletResponse,
			String paramInputStream, Map<String, Object> paramMap,
			List paramList, String nomeRelatorio, User user) throws ReportException, IOException {

//		String instanceLogo = user.getInstance().getInstanceLogo();

//		ImageIcon logoRel = new ImageIcon(ReportUtils.class.getResource("/reports/image/" + instanceLogo ));
//		paramMap.put("LOGO", logoRel.getImage());
    	
    	byte[] arrayOfByte = exportToPdf(paramInputStream, paramMap, paramList);
		
        paramHttpServletResponse.setContentLength(arrayOfByte.length);
        paramHttpServletResponse.setContentType("application/pdf");
        paramHttpServletResponse.setHeader("Content-disposition", "download; filename=" + nomeRelatorio +".pdf");
        ServletOutputStream localServletOutputStream = paramHttpServletResponse.getOutputStream();
        localServletOutputStream.write(arrayOfByte);
        localServletOutputStream.flush();
        localServletOutputStream.close();
    }
    
    
	@SuppressWarnings("rawtypes")
	public static void exportXlsToResponse(HttpServletResponse response,
			String paramInputStream, Map<String, Object> paramMap,
			List paramList, String nomeRelatorio, Usuario user) throws ReportException,
			IOException {
		
//		String instanceLogo = user.getInstance().getInstanceLogo();

//		ImageIcon logoRel = new ImageIcon(ReportUtils.class.getResource("/reports/image/" + instanceLogo ));
//		paramMap.put("LOGO", logoRel.getImage());
		
		byte[] arrayOfByte = exportToXls(paramInputStream, paramMap, paramList);
		
		OutputStream outputStream = response.getOutputStream();
		response.setContentType("application/excel");
		response.setHeader("Content-Disposition", "attachment; filename=" + nomeRelatorio + ".xlsx");
		outputStream.write(arrayOfByte);
		outputStream.flush();
		outputStream.close();
	}
    
	
    @SuppressWarnings("rawtypes")
	public static void exportXlsToResponseNSheets(HttpServletResponse response,
			String paramInputStream, Map<String, Object> paramMap,
			List<List> paramList, String nomeRelatorio, User user) throws ReportException,
			IOException {
    	
//    	String instanceLogo = user.getInstance().getInstanceLogo();

//		ImageIcon logoRel = new ImageIcon(ReportUtils.class.getResource("/reports/image/" + instanceLogo ));
//		paramMap.put("LOGO", logoRel.getImage());
    	
        byte[] arrayOfByte = exportToXlsNSheets(paramInputStream, paramMap, paramList);
        
        OutputStream outputStream = response.getOutputStream();  
        response.setContentType("application/excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + nomeRelatorio +".xlsx");  
        outputStream.write(arrayOfByte);
        outputStream.flush();
        outputStream.close();  
    }
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static byte[] exportToXlsNSheets(String paramInputStream, Map paramMap, List<List> paramList)
            throws ReportException {
    	
        ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
        
        try {
        	
            JRXlsxExporter localJRXlsExporter = new JRXlsxExporter();
            JasperReport localJasperReport = loadReport(paramInputStream);
            List<JasperPrint> reportList = new ArrayList<JasperPrint>();
            Iterator it = paramList.iterator();
            
            while (it.hasNext()){
            	List itNext = (List) it.next();
            	JasperPrint localJasperPrint = JasperFillManager.fillReport(localJasperReport, paramMap, new JRBeanCollectionDataSource(itNext, false));
            	reportList.add(localJasperPrint);
            }
            
            localJRXlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT_LIST, reportList);
            localJRXlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, localByteArrayOutputStream);
            localJRXlsExporter.exportReport();
            
        } catch (Exception localException) {
            Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, null, localException);
            
            throw new ReportException(localException.getMessage());
        }
        
        return localByteArrayOutputStream.toByteArray();
    }
}
